package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.CreateSceneResult;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.event.RefreshSceneIntentEvent;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.dialog.BottomDelayTimeDialog;
import com.qiantu.phone.ui.dialog.BottomDeviceDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.shotview.MusicShotView;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.utils.TempDataHolder;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.Set;

public abstract class EditSceneBaseActivity extends AppActivity {
    public SceneDetailBean sceneDetailBean;
    protected boolean isCreate;
    protected boolean isRecommendScene;
    protected RecyclerView mRecyclerView;
    //初始的是否常用
    protected boolean initFavourite;
    protected String initFavouriteRoomSerialNo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_scene1;
    }

    @Override
    protected void initView() {
        mRecyclerView = findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        getTitleBar().getRightView().setSelected(false);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //重新跳转到编辑页
        if(sceneDetailBean == null){
            return;
        }
        sceneDetailBean = TempDataHolder.getEditSceneDetailBean(sceneDetailBean.getSceneType());
        if (sceneDetailBean == null) {
            return;
        }
        if(getAdapter() != null){
            getAdapter().notifyDataSetChanged();
        }
        checkRightClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onLeftClick(View view) {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        String tip = isCreate? getString(R.string.create_back_hint) : getString(R.string.edit_back_hint);
        if (getTitleBar().getRightView().isSelected()){//已经有数据修改
            new ConfirmHintDialog.Builder(this)
                    .setLeftBtnText(getString(R.string.cancel))
                    .setRightBtnText(getString(R.string.back))
                    .setContent(tip)
                    .setLeftBtnStrongHint(true)
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            dialog.dismiss();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            dialog.dismiss();
                            finish();
                        }
                    })
                    .show();
        }else {
            finish();
        }
    }

    @Override
    public void finish() {
        //推荐场景再推荐场景动作页面清除缓存。否则当前页面返回推荐场景动作页面，再次进入，动作被清空了
        if(!isRecommendScene){
            TempDataHolder.clearEditSceneDetailBean(sceneDetailBean.getSceneType());
        }
        super.finish();
    }

    @Override
    public void onRightClick(View view) {
        if(!submitCheck()){
            return;
        }
        if (isCreate){
            LLHttpManager.sceneCreate(this, sceneDetailBean, new HttpCallback<HttpData<CreateSceneResult>>(this){
                @Override
                public void onSucceed(HttpData<CreateSceneResult> result) {
                    super.onSucceed(result);
                    SceneBean scene = result.getData().getCreateSceneDto();
                    LLSceneDBManager.getInstance(getContext()).put(scene);
                    TempDataHolder.clearEditSceneDetailBean(sceneDetailBean.getSceneType());
                    switch (scene.getSceneType()){
                        case 1:
                            EventBus.getDefault().post(new RefreshSceneEvent(scene.getRoomSerialNo(), scene.getIsFavourite()));
                            //添加常用场景，并且当前没有常用场景和设备就要刷新首页楼层或者房间栏
                            if(sceneDetailBean.getFavourite() != null && sceneDetailBean.getFavourite()){
                                EventBus.getDefault().post(new UpdateFavouriteEvent(UpdateFavouriteEvent.TYPE_ADD));
                            }
                            //如果从触发条件页面进来，完成后关闭触发条件页面
                            ActivityManager.getInstance().finishActivity(AddConditionActivity.class);
                            //如果从推荐场景页面进来，完成后关闭触发条件页面
                            ActivityManager.getInstance().finishActivity(RecommendSceneDeviceActionActivity.class);
                            ActivityManager.getInstance().finishActivity(SceneAddGuideActivity.class);
                            break;
                        case 3:
                            EventBus.getDefault().post(new RefreshSceneIntentEvent());
                            break;
                    }
//                    startActivity(HomeActivity.class);
                    finish();
                }
            });
        }else {
            LLHttpManager.sceneSave(this, sceneDetailBean, new HttpCallback<HttpData<CreateSceneResult>>(this){
                @Override
                public void onSucceed(HttpData<CreateSceneResult> result) {
                    super.onSucceed(result);
                    SceneBean scene = result.getData().getCreateSceneDto();
                    LLSceneDBManager.getInstance(getContext()).put(scene);
                    TempDataHolder.clearEditSceneDetailBean(sceneDetailBean.getSceneType());
                    switch (scene.getSceneType()){
                        case 1:
                            boolean needUpdateFavourite = false;
                            //常用有改变
                            if(initFavourite != sceneDetailBean.getFavourite()){
                                needUpdateFavourite = true;
                                EventBus.getDefault().post(new UpdateFavouriteEvent(sceneDetailBean.getFavourite() ? UpdateFavouriteEvent.TYPE_ADD : UpdateFavouriteEvent.TYPE_CANCEL));
                            }
                            if(!sceneDetailBean.getRoomSerialNo().equals(initFavouriteRoomSerialNo)){
                                //更改房间的需要刷新2个房间的场景
                                EventBus.getDefault().post(new RefreshSceneEvent());
                            }else{
                                EventBus.getDefault().post(new RefreshSceneEvent(scene.getRoomSerialNo(), needUpdateFavourite));
                            }
                            EventBus.getDefault().post(new RefreshFloorRoomEvent());
                            //如果从触发条件页面进来，完成后关闭触发条件页面
                            ActivityManager.getInstance().finishActivity(AddConditionActivity.class);
                            break;
                        case 3:
                            EventBus.getDefault().post(new RefreshSceneIntentEvent());
                            break;
                    }
//                    startActivity(HomeActivity.class);
                    finish();
                }
            });
        }
    }

    protected abstract boolean submitCheck();

    protected abstract RecyclerView.Adapter getAdapter();

    public void checkRightClick(){
        getTitleBar().getRightView().setSelected(hasModifyData());
    }

    private boolean hasModifyData(){
        if (sceneDetailBean == null) return false;
        if (!TextUtils.isEmpty(sceneDetailBean.getName())) return true;
        if (!TextUtils.isEmpty(sceneDetailBean.getImage())) return true;
        if (!TextUtils.isEmpty(sceneDetailBean.getRoomSerialNo())) return true;
        //新建时开关绑定设置后，需要提示是否保存
        if (isCreate && sceneDetailBean.getSwitchBindList() != null && sceneDetailBean.getSwitchBindList().size() > 0) return true;
        if (sceneDetailBean.getSceneTasks() != null && !sceneDetailBean.getSceneTasks().isEmpty()) return true;
        return false;
    }

    private BottomDeviceDialog mDeviceDialog;
    public void showDeviceDialog(SceneDetailBean.SceneTaskBean sceneTaskBean, int position) {
        SceneDetailBean.SceneDeviceInstructBean instructBean = sceneTaskBean.getSceneDeviceInstruct();
        if(instructBean == null){
            return;
        }
        DeviceBean deviceBean = LLDeviceDBManager.getInstance(getContext()).get(instructBean.getDeviceItemSerialNo());
        mDeviceDialog = new BottomDeviceDialog(this){
            @Override
            public void onSave(Map<String, String> statusJson, List<DeviceBean> deviceBeans) {
                instructBean.getDeviceItemStateData().setStatus(statusJson);
                getAdapter().notifyItemChanged(position);
                checkRightClick();
            }
        };
        new XPopup.Builder(this)
                .dismissOnBackPressed(true)
                .enableDrag(false)
                .asCustom(mDeviceDialog);
        mDeviceDialog.setDeviceBean(deviceBean, instructBean.getDeviceItemStateData().getStatus());
        mDeviceDialog.show();
    }

    public void showGroupDialog(SceneDetailBean.SceneTaskBean sceneTaskBean, int position) {
        SceneDetailBean.SceneDeviceGroupInstruct instructBean = sceneTaskBean.getSceneDeviceGroupInstruct();
        if(instructBean == null){
            return;
        }
        DeviceBean deviceBean = LLDeviceDBManager.getInstance(getContext()).get(instructBean.getDeviceGroupSerialNo());
        mDeviceDialog = new BottomDeviceDialog(this){
            @Override
            public void onSave(Map<String, String> statusJson,List<DeviceBean> deviceBeans) {
                instructBean.getStateData().setStatus(statusJson);
                getAdapter().notifyItemChanged(position);
                checkRightClick();
            }
        };
        new XPopup.Builder(this)
                .dismissOnBackPressed(true)
                .enableDrag(false)
                .asCustom(mDeviceDialog);
        mDeviceDialog.setDeviceBean(deviceBean, instructBean.getStateData().getStatus());
        mDeviceDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MusicShotView.requCode){
            if (resultCode== Activity.RESULT_OK){
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("songname",data.getStringExtra("musicName"));
                    jsonObject.put("songpicurl",data.getStringExtra("picUrl"));
                    jsonObject.put("musicid",data.getStringExtra("musicid"));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                mDeviceDialog.setMusicID_dialog(jsonObject);
            }
        }
    }

}